package com.mycompony.shopping.shangguan.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.mycompony.shopping.shangguan.sys.dao.MenuMapper;
import com.mycompony.shopping.shangguan.sys.model.Auth;
import com.mycompony.shopping.shangguan.sys.model.Menu;
import com.mycompony.shopping.shangguan.sys.model.MenuExample;
import com.mycompony.shopping.shangguan.sys.service.MenuService;
import com.mycompony.shopping.shangguan.sys.util.Constant;

public class MenuServiceImpl implements MenuService {

	private MenuMapper menuMapper = null;

	public List<Menu> queryRootMenuList(List<Auth> authList) {

		MenuExample menuExample = new MenuExample();

		List<String> auths = new ArrayList<String>();

		for (Auth auth : authList) {
			if (auth == null || StringUtils.isEmpty(auth.getAuthid())) {
				break;
			}
			auths.add(auth.getAuthid());
		}
		menuExample.createCriteria().andAuthidIn(auths).andParentidIsNull()
				.andActiveEqualTo(Constant.active_success);

		menuExample.setOrderByClause("indexnum asc ");

		return menuMapper.selectByExample(menuExample);
	}

	public List<Menu> queryChildrenMenuList(Menu menu, List<Auth> authList) {

		if (menu == null || StringUtils.isEmpty(menu.getMenuid())) {
			return null;
		}

		MenuExample menuExample = new MenuExample();

		List<String> auths = new ArrayList<String>();

		for (Auth auth : authList) {
			if (auth == null || StringUtils.isEmpty(auth.getAuthid())) {
				break;
			}
			auths.add(auth.getAuthid());
		}
		menuExample.createCriteria().andAuthidIn(auths).andParentidEqualTo(
				menu.getMenuid()).andActiveEqualTo(Constant.active_success);

		menuExample.setOrderByClause("indexnum asc ");

		return menuMapper.selectByExample(menuExample);
	}

	public MenuMapper getMenuMapper() {
		return menuMapper;
	}

	public void setMenuMapper(MenuMapper menuMapper) {
		this.menuMapper = menuMapper;
	}

	public List<Menu> queryLeftMenuList(List<Auth> authList) {
		List<Menu> roots = queryRootMenuList(authList);
		for (Menu root : roots) {
			List<Menu> children = queryChildrenMenuList(root, authList);
			root.setChildren(children);
		}
		return roots;
	}

	public void addMenu(Menu menu) {
		if (menu == null) {
			return;
		}
		menuMapper.insert(menu);
	}

	public void deleteMenu(Menu menu) {

		menuMapper.deleteByPrimaryKey(menu.getId());
	}

	public void updateMenu(Menu menu) {
		menuMapper.updateByPrimaryKey(menu);
	}

	public List<Menu> queryAllMenuList() {
		return menuMapper.selectByExample(null);
	}

}
